package com.sqoq.downloader3.ui

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.FrameLayout
import android.widget.ImageView
import com.sqoq.downloader3.R
import me.jessyan.autosize.utils.AutoSizeUtils

class MProgress_ddg : FrameLayout {
    private var translateAnimation: TranslateAnimation? = null
    private var progress: ImageView

    constructor(context: Context) : super(context) {}
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
    }

    constructor(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
    }

    init {

        LayoutInflater.from(context).inflate(R.layout.mprogress_ddg, this)
        progress = findViewById<ImageView>(R.id.progress)
    }

    fun start() {
        var start = false
        viewTreeObserver.addOnDrawListener {
            if (width > 0 && start.not()) {
                start = true
                translateAnimation = TranslateAnimation(
                    -AutoSizeUtils.dp2px(context, 52f).toFloat(),
                    width.toFloat(), 0f, 0f
                )
                translateAnimation?.duration = 1700 //动画时长
                translateAnimation?.repeatCount = -1
                translateAnimation?.repeatMode = Animation.RESTART
                translateAnimation?.fillAfter = true //true ：view停留在动画结束的地方。false ：动画结束后 view 返回原位

                progress.startAnimation(translateAnimation)
            }
        }

    }

    override fun setVisibility(visibility: Int) {
        super.setVisibility(visibility)
        if (View.VISIBLE == visibility) {
            start()
        } else {
            progress.clearAnimation()
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        progress.clearAnimation()
    }
}